package com.shixulin.oss;

import com.aliyun.oss.*;
import com.aliyun.oss.model.ObjectMetadata;
import com.shixulin.entity.filess;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URL;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class handleFile {
    @Value("${aliyun.oss.endpoint}")
    private String ALIYUN_OSS_ENDPOINT;
    @Value("${aliyun.oss.accessKeyId}")
    private String ALIYUN_OSS_ACCESSKEYID;
    @Value("${aliyun.oss.accessKeySecret}")
    private String ALIYUN_OSS_ACCESSKEYSECRET;
    @Value("${aliyun.oss.bucketName}")
    private String ALIYUN_OSS_BUCKETNAME;
    //域名
    private static final String DOMAIN = "http://shixulin.com";
    public filess uploadFile(MultipartFile multipartFile) throws IOException {
        OSSClient ossClient = new OSSClient(ALIYUN_OSS_ENDPOINT, ALIYUN_OSS_ACCESSKEYID, ALIYUN_OSS_ACCESSKEYSECRET);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// 获取文件名
        String fileName = multipartFile.getOriginalFilename();
// 获取文件后缀名
        assert fileName != null;
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 最后上传生成的文件名
        String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
// oss中的文件夹名
        String objectName = "studyFile/"+ sdf.format(new Date()) + "/" + finalFileName;
// 创建上传文件的元信息，可以通过文件元信息设置HTTP header(设置了才能通过返回的链接直接访问)。
//        ObjectMetadata objectMetadata = new ObjectMetadata();
//        objectMetadata.setContentType("image/jpg");
        //文件预览
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setHeader("Content-Disposition", "inline");
// 文件上传
        ossClient.putObject(ALIYUN_OSS_BUCKETNAME, objectName, new ByteArrayInputStream(multipartFile.getBytes()),metadata);
// 设置URL过期时间为10个月。
        Date expiration = new Date(System.currentTimeMillis() + 10L * 30 * 24 * 3600 * 1000);
        //获取url

//        String url = ossClient.generatePresignedUrl(ALIYUN_OSS_BUCKETNAME, objectName, expiration).toString();
        URL signedUrl = ossClient.generatePresignedUrl(ALIYUN_OSS_BUCKETNAME, objectName, expiration);
        String path = signedUrl.getPath();
        String url = DOMAIN + path ;
        ossClient.shutdown();
        filess filess_f = new filess(url,objectName);
        return filess_f;
    }

    public boolean deleteFile(String fileName){
        try {
            //创建一个实例
            OSSClient ossClient = new OSSClient(ALIYUN_OSS_ENDPOINT, ALIYUN_OSS_ACCESSKEYID, ALIYUN_OSS_ACCESSKEYSECRET);
            ossClient.deleteObject(ALIYUN_OSS_BUCKETNAME,fileName);
            return true;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}